package com.ruiyi.adrobot.service.taskdetail.impl;

import com.ruiyi.adrobot.beans.TaskDetail;
import com.ruiyi.adrobot.mongo.taskdetail.TaskDetailRepository;
import com.ruiyi.adrobot.service.taskdetail.TaskDetailService;
import com.ruiyi.adrobot.component.TaskExcuter;
import com.ruiyi.adrobot.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Service;

/**
 * Created by Lenovo on 2017/5/8.
 */
@Service
@EnableScheduling
public class TaskDetailServiceImpl implements TaskDetailService {
    @Autowired
    private TaskDetailRepository taskDetailRepository;

    @Override
    public String insert(TaskDetail taskDetail) {
        taskDetail.setCreateDate(DateUtil.getCurrentTime());
        taskDetail = taskDetailRepository.insert(taskDetail);
        return taskDetail.getId();
    }

    /**
     * @param id
     */
    @Override
    public void stopTaskById(String id) {
        TaskExcuter.stopTaskList.add(id);
        TaskExcuter.queueMap.remove(id);
        taskDetailRepository.findAndMudifFinishedById(id, true);
    }

    @Override
    public TaskDetail updateTaskByNum(String taskDetailId, Integer num, Update update) {
        return taskDetailRepository.updateTaskByNum(taskDetailId, num, update);
    }

    @Override
    public TaskDetail updateById(String taskDetailId, Update update) {
        return taskDetailRepository.updateById(taskDetailId, update);
    }

    @Override
    public TaskDetail.Task findTaskByNum(String taskDetailId, Integer num) {
        return taskDetailRepository.findTaskByNum(taskDetailId, num);
    }

    /**
     * 动态获取IP云acces
     * 每天晚上12点触发一次
     * 1.查询出近两日所有的未统计的任务
     */
//    @Override
//    @Scheduled(cron = "0 59 23 * * ?")
//    public void buildReport() {
//        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
//        Calendar cal = Calendar.getInstance();
//        String endDate = format.format(cal.getTime()) + " 23:59:59";
//        cal.add(Calendar.DAY_OF_MONTH, -1); // 取当前日期的前一天.
//        String startDate = format.format(cal.getTime()) + " 00:00:00";
//        List<TaskReport> taskReports = taskDetailRepository.findByReportedAndCreateDateBetween(startDate, endDate);
//        for (TaskReport taskReport : taskReports) {
//            taskReport.setReportDate(endDate);
//            taskReportRepository.insert(taskReport);
//        }
//    }

}
